import axios from "axios";
import {Message} from 'element-ui';

axios.defaults.withCredentials = true;

class HttpRequest {
  constructor(baseUrl = '') {
    this.baseUrl = baseUrl;
    this.queue = {};
  }
  destroy(url) {
    delete this.queue[url];
  }
  interceptors(instance, url) {
    // 请求拦截
    instance.interceptors.request.use(
      config => {
        this.queue[url] = true;
        return config;
      },
      error => {
        return Promise.reject(error);
      }
    );
    // 响应拦截
    instance.interceptors.response.use(
      res => {
        this.destroy(url);
        const {data, status} = res;
        if (status === 200) {
          return data;
        } else {
          return Promise.reject(res);
        }
      },
      error => {
        this.destroy(url);
        let errorInfo = error.response;
        if (!errorInfo) {
          const {
            request: {statusText, status},
            config
          } = JSON.parse(JSON.stringify(error));
          errorInfo = {
            statusText,
            status,
            request: {responseURL: config.url}
          };
        }
        const {data, status} = errorInfo;
        if (status === 500) {
          Message.error("服务器开小差了");
          //window.location.href = window.location.origin;
        } else {
          Message.error(data.data?.error_msg || '未知异常');
          //window.location.href = window.location.origin;
        }

        return Promise.reject(data);
      }
    );
  }
  request(options) {
    const instance = axios.create();

    if (options.mock) {
      return options.mock;
    }

    // 清除空格
    const dataTirm = (data) => {
      const value = {...data};

      for (let key in value) {
        if (typeof value[key] === 'string') {
          value[key] = value[key].trim();
        }
      }
      return value;
    };

    options.url = `${this.baseUrl}/${options.url}`;
    options.data = dataTirm(options.data);

    this.interceptors(instance, options.url);
    return instance(options);
  }
}

export default HttpRequest;